/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.minimalismstyle.fresh.common.core.spring

import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.stereotype.Component
import kotlin.reflect.KClass

/**
 * spring上下文工具对象
 * @author maoxiaodong
 */
@Component
class SpringContextUtils : ApplicationContextAware {

    override fun setApplicationContext(applicationContext: ApplicationContext) {
        context = applicationContext
    }

    companion object {
        private lateinit var context: ApplicationContext

        /**
         * 根据bean id获取bean
         * @param id bean Id
         */
        @Suppress("UNCHECKED_CAST")
        fun <T> getBean(id: String): T {
            return context.getBean(id) as T
        }

        /**
         * 根据java clazz获取bean
         * @param clazz
         */
        fun <T> getBean(clazz: Class<T>): T {
            return context.getBean(clazz)
        }

        /**
         * 根据KClass获取bean
         * @param clazz
         */
        fun <T: Any> getBean(clazz: KClass<T>): T {
            return context.getBean(clazz.java)
        }

        /**
         * 根据KClass获取beans
         * @param clazz
         */
        fun <T: Any> getBeansOfType(clazz: KClass<T>): Map<String, T> {
            return context.getBeansOfType(clazz.java)
        }

        /**
         * 判断bean id是否存在
         * @param id bean Id
         */
        fun containsBean(id: String): Boolean {
            return context.containsBean(id)
        }
    }
}